import FungibleToken from "../contracts/FungibleToken.cdc"
import NonFungibleToken from "../contracts/NonFungibleToken.cdc"
import FlowToken from "../contracts/FlowToken.cdc"
import NftEggsNFT from "../contracts/NftEggsNFT.cdc"
import NftEggsStore from "../contracts/NftEggsStore.cdc"

transaction(saleItemID: UInt64, saleItemPrice: UFix64) {
    let flowReceiver: Capability<&FlowToken.Vault{FungibleToken.Receiver}>
    let feeReceiver: Capability<&FlowToken.Vault{FungibleToken.Receiver}>
    let NftEggsNFTProvider: Capability<&NftEggsNFT.Collection{NonFungibleToken.Provider, NonFungibleToken.CollectionPublic}>
    let storefront: &NftEggsStore.Storefront
	
    prepare(acct: AuthAccount) {
        // We need a provider capability, but one is not provided by default so we create one if needed.
        let NftEggsNFTCollectionProviderPrivatePath = /private/NftEggsNFTCollectionProviderForNftEggsStore

        self.flowReceiver = acct.getCapability<&FlowToken.Vault{FungibleToken.Receiver}>(/public/flowTokenReceiver)!
        assert(self.flowReceiver.borrow() != nil, message: "Missing or mis-typed FlowToken receiver")
		
        self.feeReceiver = getAccount(0xf3fcd2c1a78f5eee).getCapability<&FlowToken.Vault{FungibleToken.Receiver}>(/public/flowTokenReceiver)!
        assert(self.feeReceiver.borrow() != nil, message: "Missing or mis-typed FlowToken receiver")

        if !acct.getCapability<&NftEggsNFT.Collection{NonFungibleToken.Provider, NonFungibleToken.CollectionPublic}>(NftEggsNFTCollectionProviderPrivatePath)!.check() {
            acct.link<&NftEggsNFT.Collection{NonFungibleToken.Provider, NonFungibleToken.CollectionPublic}>(NftEggsNFTCollectionProviderPrivatePath, target: /storage/NFTCollection)
        }

        self.NftEggsNFTProvider = acct.getCapability<&NftEggsNFT.Collection{NonFungibleToken.Provider, NonFungibleToken.CollectionPublic}>(NftEggsNFTCollectionProviderPrivatePath)!
        assert(self.NftEggsNFTProvider.borrow() != nil, message: "Missing or mis-typed NftEggsNFT.Collection provider")

        self.storefront = acct.borrow<&NftEggsStore.Storefront>(from: NftEggsStore.StorefrontStoragePath)
            ?? panic("Missing or mis-typed NftEggsStore Storefront")
    }

    execute {
        let saleCut = NftEggsStore.SaleCut(
            receiver: self.flowReceiver,
            amount: saleItemPrice*0.9
        )
		
		let saleCut2 = NftEggsStore.SaleCut(
            receiver: self.feeReceiver,
            amount: saleItemPrice*0.1
        )
		
        self.storefront.createListing(
            nftProviderCapability: self.NftEggsNFTProvider,
            nftType: Type<@NftEggsNFT.NFT>(),
            nftID: saleItemID,
            salePaymentVaultType: Type<@FlowToken.Vault>(),
            saleCuts: [saleCut,saleCut2]
        )
    }
}
